package com.qingmi.farmer.ui.trolley;

import android.view.View;
import android.widget.CheckBox;

import com.luck.picture.lib.rxbus2.RxBus;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.luck.picture.lib.rxbus2.ThreadMode;
import com.qingmi.farmer.BR;
import com.qingmi.farmer.R;
import com.qingmi.farmer.data.UserData;
import com.qingmi.farmer.data.model.Trolley;
import com.qingmi.farmer.data.repository.data.GoodsDataRepository;
import com.qingmi.farmer.databinding.FragmentBuyTrolleyBinding;
import com.qingmi.farmer.event.BuyTrolleyDataChangeEvent;
import com.qingmi.farmer.event.UserLoginChangeEvent;
import com.wjjun.base.ui.base.ListFragment;
import com.qingmi.farmer.ui.buy.GoodsDetailActivity;
import com.qingmi.farmer.viewmodel.TrolleyItemViewModel;
import com.qingmi.farmer.window.EditCountDialog;
import com.wjjun.basemvpvm.data.exception.MyException;
import com.wjjun.basemvpvm.data.observer.DefaultObserver;
import com.wjjun.basemvpvm.viewmodel.BaseViewModel;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import me.tatarka.bindingcollectionadapter2.ItemBinding;


/**
 * 买入购物车
 */
public class BuyTrolleyFragment extends ListFragment<BuyTrolleyViewModel, FragmentBuyTrolleyBinding> {

    private EditCountDialog editCountDialog;

    @Inject
    GoodsDataRepository goodsDataRepository;

    @Inject
    UserData userData;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_buy_trolley;
    }

    @Override
    protected BuyTrolleyViewModel initViewModel() {
        return new BuyTrolleyViewModel();
    }

    @Override
    protected void initContent() {
        goodsDataRepository.bind(this);
        super.initContent();
        commListViewModel.setEnableLoadMore(false);
        commListViewModel.setEmpty(getString(R.string.error_trolley_is_empty), R.drawable.ic_trolley_empty);
        RxBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTrolleyDataChange(BuyTrolleyDataChangeEvent event) {
        notifyDataChange();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserLoginChange(UserLoginChangeEvent event) {
        notifyDataChange();
    }


    @Override
    public void onListItemBind(ItemBinding itemBinding, int position, Object item) {
        itemBinding.set(BR.viewModel, R.layout.layout_item_trolley).bindExtra(BR.presenter, viewGroupPresenter);
    }


    @Override
    public void onClick(View view) {
        if (getActivity() == null) {
            showToast(R.string.error_activity_is_null);
            return;
        }
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_clear://快速清理
                break;
            case R.id.tv_delete://删除
                break;
            case R.id.tv_reserve://提交预定
                if (data.isEmpty() || viewModel.selectGoods.isEmpty()) {
                    return;
                }
                break;
            case R.id.cb_all_check://全选
                if (view instanceof CheckBox) {
                    selectAll(((CheckBox) view).isChecked());
                }
                break;
        }
    }


    /**
     * 隐藏管理栏
     */
    private void hideManagerBar() {
        viewModel.hideManagerBar();
        updateTotalPrice();
        if (getParentFragment() != null && (getParentFragment() instanceof TrolleyFragment)) {
            ((TrolleyFragment) getParentFragment()).updateRightTxt();
        }
    }

    @SuppressWarnings("unchecked")
    private void selectAll(boolean check) {
        viewModel.selectGoods.clear();
        if (check) {//全选
            viewModel.selectGoods.addAll(data);
        }

        for (Object item : data) {
            if (item instanceof TrolleyItemViewModel) {
                ((TrolleyItemViewModel) item).check.set(check);
            }
        }
        updateTotalPrice();
    }


    @SuppressWarnings("ConstantConditions")
    @Override
    protected void onListItemClick(View view, BaseViewModel item) {
        super.onListItemClick(view, viewModel);
        if (getActivity() == null) {
            showToast(R.string.error_activity_is_null);
            return;
        }
        if (item instanceof TrolleyItemViewModel) {
            switch (view.getId()) {
                case R.id.cb_check: //选中
                    if (viewModel.selectGoods.contains(item)) {
                        viewModel.selectGoods.remove(item);
                    } else {
                        viewModel.selectGoods.add((TrolleyItemViewModel) item);
                    }
                    updateTotalPrice();
                    break;
                case R.id.vg_item:
                    GoodsDetailActivity.start(getActivity(), ((TrolleyItemViewModel) item).goodsInfo.getGoodId(),
                            ((TrolleyItemViewModel) item).count.get(), ((TrolleyItemViewModel) item).id);
                    break;
                case R.id.tv_count:
                    break;
            }
        }
    }

    public void toggleShowManagerBar() {
        if (data.isEmpty()) {
            return;
        }
        viewModel.toggleShowManagerBar();
        if (getParentFragment() != null && (getParentFragment() instanceof TrolleyFragment)) {
            ((TrolleyFragment) getParentFragment()).updateRightTxt();
        }
    }

    public boolean isShowManagerBar() {
        if (viewModel == null || viewModel.showManagerBar.get() == null) {
            return false;
        } else {
            return viewModel.showManagerBar.get();
        }
    }

    @Override
    public void refreshData(boolean init) {
        if (!UserData.getInstance().isLogin()) {
            showLogin();
            return;
        }
        super.refreshData(init);
        goodsDataRepository.getTrolley(new DefaultObserver<List<Trolley>>() {
            @Override
            public void onNext(List<Trolley> trolleys) {
                List<TrolleyItemViewModel> list = new ArrayList<>();
                if (trolleys != null) {
                    for (Trolley item : trolleys) {
                        TrolleyItemViewModel itemViewModel = new TrolleyItemViewModel(item);
                        list.add(itemViewModel);
                    }
                }
                resetData(list);
                viewModel.selectGoods.clear();
                updateTotalPrice();
                if (data.isEmpty()) {
                    hideManagerBar();
                }
            }

            @Override
            public void onError(MyException e) {
                setError(e.getMessage());
            }
        });
    }

    @SuppressWarnings("ConstantConditions")
    private void updateTotalPrice() {
        double totalPrice = 0;

        for (Object object : viewModel.selectGoods) {
            if (object instanceof TrolleyItemViewModel) {

                TrolleyItemViewModel item = (TrolleyItemViewModel) object;
                if (item.check.get()) {
                    totalPrice += item.price.get() * item.count.get();
                }
            }
        }
        viewModel.totalPrice.set(totalPrice);
    }


}
